import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== "production";
import {
  USER_INFO,
  TOKEN,
  CONFIG
} from '@/config/cachekey';
import cache from '@/utils/cache'
console.log('===token===', cache.get(TOKEN));
export default new Vuex.Store({
  state: {
    config: cache.get(CONFIG) || {
      website: {},
      login: {},
      tabbar: [],
      style: {},
      webPage: {},
    },
    userInfo: {},
    token: cache.get(TOKEN) || null,
    temToken: null,
  },
  getters: {
    userInfo: state => state.userInfo || {},
    token: state => state.token,
    isLogin: state => !!state.token,
    appConfig: state => state.config,
    temToken: state => state.temToken || null,
    websiteConfig: (state) => state.config.website || {},
    loginConfig: (state) => state.config.login || {},
    getTabbarConfig: (state) => state.config.tabbar || [],
    getStyleConfig: (state) => state.config.style || {},
    getH5Config: (state) => state.config.webPage || {}
  },
  mutations: {
    LOGIN(state, token) {
      // state.token = opt.token;
      // cache.set(TOKEN, opt.token, 59 * 24 * 60 * 60);
      // this.dispatch('getUser')

      state.token = token
      cache.set(TOKEN, token)
    },
    LOGOUT(state) {
      state.token = '';
      state.userInfo = {}
      cache.remove(TOKEN);
    },
    SET_USERINFO(state, user) {
      state.userInfo = user
    },
    SET_CONFIG(state, data) {
      state.config = Object.assign(state.config, data)
      cache.set(CONFIG, state.config);
    }
  },
  actions: {
    // getImageUrl(context, url) {
    //   return url ? (context.state.config.domain + url) : ''
    // },
    async getConfig(context) {
      const data = await uni.$u.api.getConfig()
      context.commit('SET_CONFIG', data)
      // this.config = data
    },
    async getUser({
      state,
      commit
    }) {
      // var data = await uni.$u.api.getUser()
      const data = await uni.$u.api.getUserCenter({
        token: state.token || state.temToken
      })
      // this.userInfo = data
      commit('SET_USERINFO', data)

    },
    login(context, token) {
      context.commit('LOGIN', token)
    },
    logout(context) {
      context.commit('LOGOUT')
    },
  },
  strict: debug
});